package com.sdp.wx.handleImpl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.sdp.core.bizc.utils.ApplicationContextUtils;
import com.sdp.core.bizc.vo.BusinessContext;
import com.sdp.wx.controller.WxRepairCodeController;
import com.sdp.wx.db.wx_warehouse_info.entity.WxWarehouseInfo;
import com.sdp.wx.db.wx_warehouse_info.service.IWxWarehouseInfoService;
import com.sdp.wx.db.wx_warehouse_right.service.IWxWarehouseRightService;
import com.sdp.wx.db.wx_wz_input.entity.WxWzInput;
import com.sdp.wx.db.wx_wz_input.service.IWxWzInputService;
import com.sdp.wx.db.wx_wz_input_detail.entity.WxWzInputDetail;
import com.sdp.wx.db.wx_wz_input_detail.service.IWxWzInputDetailService;
import com.sdp.wx.db.wx_wz_now_num.service.IWxWzNowNumService;
import com.sdp.wx.db.wx_wz_output.entity.WxWzOutput;
import com.sdp.wx.db.wx_wz_output.service.IWxWzOutputService;
import com.sdp.wx.db.wx_wz_output_detail.entity.WxWzOutputDetail;
import com.sdp.wx.db.wx_wz_output_detail.service.IWxWzOutputDetailService;
import com.sdp.wx.handle.WzInOutPutHandle;
import com.sdp.wx.utils.CurrentLoginEmp;
import com.sdp.wx.utils.WxConstants;

@Component
public class WzScrapOutPutHandleImpl extends WzInOutPutHandle{
	
	@Autowired
	private CurrentLoginEmp currentLoginEmp;
	
	@Autowired
	private IWxWarehouseInfoService iWxWarehouseInfoService;
	
	@Autowired
	private IWxWarehouseRightService iWxWarehouseRightService;
	
	@Autowired
	private IWxWzNowNumService iWxWzNowNumService;
	
	@Autowired
	private IWxWzInputDetailService iWxWzInputDetailService;
	
	@Autowired
	private IWxWzInputService iWxWzInputService;
	
	@Autowired
	private WxRepairCodeController wxRepairCodeController;
	
	@Autowired
	private IWxWzOutputService iWxWzOutputService;
	
	@Autowired
	private IWxWzOutputDetailService iWxWzOutputDetailService;
	


	@Override
	public BusinessContext execute(BusinessContext businessContext) {
		
		return ApplicationContextUtils.getBean(WzScrapOutPutHandleImpl.class).scrapOutput(businessContext);
	}
	
	@Transactional(rollbackFor=Exception.class)
	public BusinessContext scrapOutput(BusinessContext businessContext) {
		
		JSONObject emp = currentLoginEmp.getCurrentLoginInfo();
		if(StringUtils.isEmpty(emp)) {
			businessContext.setMessage("请先登录系统");
			businessContext.setSuccess(false);
			return businessContext;
		}
		
		List<WxWzOutputDetail> wzList = businessContext.get(WxWzOutputDetail.class);
		WxWzOutput output = businessContext.get(WxWzOutput.class);
		if(output==null || wzList==null || wzList.size()==0) {
			businessContext.setSuccess(false);
			businessContext.setMessage("报废器材不存在，不能出库");
			return businessContext;
		}
		
		//判断仓库是否锁定
		WxWarehouseInfo warehouseInfo = iWxWarehouseInfoService.queryWxWarehouseInfoByCode(output.getWarehouseCode());
		if(warehouseInfo==null || WxConstants.是.getCode().equals(warehouseInfo.getIsLock())) {
			businessContext.setMessage("仓库目前处于盘存状态，无法进行出库");
			businessContext.setSuccess(false);
			return businessContext;
		}
		
		//判断当前操作人是否有报废出库的权限
		boolean haveRight = iWxWarehouseRightService.isHaveRight(emp.getString("empNo"), output.getWarehouseCode(),WxConstants.库管权限_报废出库.getCode());
		if(!haveRight) {
			businessContext.setMessage("您没有此仓库的报废出库权限");
			businessContext.setSuccess(false);
			return businessContext;
		}
		
	
		//入库单内码
		List<String> inputDetailKeyIds = new ArrayList<String>();
		//入库单编号
		List<String> inputCodes = new ArrayList<>();
		//出库数量
		Map<String,BigDecimal> outputNumMap = new HashMap<>();
		
		for(WxWzOutputDetail wz : wzList) {
			inputCodes.add(wz.getInputCode());
			inputDetailKeyIds.add(wz.getKeyId());
			outputNumMap.put(wz.getKeyId(), wz.getOutputNum());
		}
		
		List<WxWzInput> inputList = iWxWzInputService.queryWzInputByCodes(inputCodes);
		if(inputList==null || inputList.size()==0) {
			businessContext.setMessage("入库信息不存在，不能进行报废出库");
			businessContext.setSuccess(false);
			return businessContext;
		}
		
		StringBuffer sbf = new StringBuffer("");
		for(WxWzInput input : inputList) {
			if(WxConstants.否.getCode().equals(input.getIsUse())) {
				sbf.append(input.getInputCode());
				sbf.append(",");
			}
			input.setIsOutput(WxConstants.是.getCode());
		}

		if(!StringUtils.isEmpty(sbf.toString())) {
			businessContext.setMessage("入库单："+sbf.toString()+"不可用，不能进行报废出库");
			businessContext.setSuccess(false);
			return businessContext;
		}
	
		
		List<WxWzInputDetail> wzInputDetailList = iWxWzInputDetailService.queryWzInputDetailByIds(inputDetailKeyIds);
		if(wzInputDetailList==null || wzInputDetailList.size()==0) {
			businessContext.setMessage("入库器材信息不存在，不能进行报废出库");
			businessContext.setSuccess(false);
			return businessContext;
		}
		if(wzInputDetailList.size()!=wzList.size()) {
			businessContext.setMessage("选择的器材库存信息发生变动，不能进行报废出库");
			businessContext.setSuccess(false);
			return businessContext;
		}
		sbf = new StringBuffer("");
		for(WxWzInputDetail wz : wzInputDetailList) {
			if(outputNumMap.containsKey(wz.getKeyId())) {
				if(wz.getNowNum().compareTo(outputNumMap.get(wz.getKeyId()))<0) {
					sbf.append("编号：");
					sbf.append(wz.getWzNo());
					sbf.append(" 名称：");
					sbf.append(wz.getWzName());
					sbf.append("出库数量大于库存！");
				}
				wz.setNowNum(wz.getNowNum().subtract(outputNumMap.get(wz.getKeyId())));
			}
		}

		if(!StringUtils.isEmpty(sbf.toString())) {
			businessContext.setMessage(sbf.toString());
			businessContext.setSuccess(false);
			return businessContext;
		}
		
		List<String> wzNoList = new ArrayList<String>();
		Map<String,BigDecimal> wzOutputNumMap = new HashMap<>();
		
		//生成出库单信息
		LocalDateTime now = LocalDateTime.now();
		if(output.getOutputTime()==null) {
			output.setOutputTime(now);
		}
		output.setOutputDate(output.getOutputTime().toLocalDate());
		output.setCreateTime(now);
		output.setOpName(emp.getString("empName"));
		output.setOpNo(emp.getString("empNo"));
		output.setOutputCode(wxRepairCodeController.getCode(WxConstants.流水号前缀_器材出库单.getCode(),WxConstants.流水号类型_器材出库单.getCode()));
		output.setIsUse(WxConstants.是.getCode());
		output.setOutputType(WxConstants.出库类型_报废出库.getCode());
		
		for(WxWzOutputDetail wz : wzList) {
			wz.setInputDetailId(wz.getKeyId());
			wz.setOutputCode(output.getOutputCode());
			wz.setCreateTime(now);
			wz.setKeyId(null);
			wzNoList.add(wz.getWzNo());
			if(wzOutputNumMap.containsKey(wz.getWzNo())) {
				wzOutputNumMap.put(wz.getWzNo(), wz.getOutputNum().add(wzOutputNumMap.get(wz.getWzNo())));
			}else {
				wzOutputNumMap.put(wz.getWzNo(), wz.getOutputNum());
			}
		}
		iWxWzOutputService.save(output);
		iWxWzOutputDetailService.saveBatch(wzList);
		
		iWxWzInputService.updateBatchById(inputList);
		iWxWzInputDetailService.updateBatchById(wzInputDetailList);
		
		//更新库存
		iWxWzNowNumService.wzNowNumSubtract(wzNoList, wzOutputNumMap, output.getWarehouseCode());
		
		return businessContext;
	}

}
